package controller

import (
	"fmt"
	"gitee.com/saxon134/go-utils/saData"
	"gitee.com/saxon134/go-utils/saData/saHit"
	"gitee.com/saxon134/go-utils/saOrm"
	"gitee.com/saxon134/workflow/api"
	"gitee.com/saxon134/workflow/db"
	"gitee.com/saxon134/workflow/db/chat"
	"gitee.com/saxon134/workflow/enum"
	"gitee.com/saxon134/workflow/errs"
	"gitee.com/saxon134/workflow/interface/ioChat"
	"gitee.com/saxon134/workflow/utils"
	"gorm.io/gorm"
	"sort"
)

func ChatList(c *api.Context) (resp *api.Response, err error) {
	var in = new(ioChat.ListRequest)
	c.Bind(in)
	if in.DemandId <= 0 {
		return nil, errs.New(errs.ErrorParams)
	}

	if in.LastId <= 0 {
		var sql = fmt.Sprintf("select id from chat where demand_id = %d", in.DemandId)
		if in.Level > 0 {
			sql += fmt.Sprintf(" and level = %d", in.Level)
		}
		if in.DemandStatus > 0 {
			sql += fmt.Sprintf(" and demand_status = %d", in.DemandStatus)
		}
		if in.Keyword != "" {
			sql += fmt.Sprintf(" and content like = '%%%s%%'", in.Keyword)
		}

		sql += fmt.Sprintf(" order by id desc limit 1")

		err = db.MySql.Raw(sql).Scan(&in.LastId).Error
		if err != nil {
			return nil, errs.New(err)
		}

		in.LastId += 1
	}

	var query = db.MySql.Table(chat.TBNChat).
		Where("demand_id = ? and status = 1", in.DemandId).
		Order("id desc").Limit(c.Paging.Limit)

	if in.LastId > 0 {
		query.Where("id < ?", in.LastId)
	}
	if in.Level > 0 {
		query.Where("level = ?", in.Level)
	}
	if in.DemandStatus > 0 {
		query.Where("demand_status = ?", in.DemandStatus)
	}
	if in.Keyword != "" {
		query.Where(fmt.Sprintf("content like '%%%s%%'", in.Keyword))
	}

	//基础信息
	var ary = make([]*chat.TblChat, 0, c.Paging.Limit)
	err = query.Find(&ary).Error
	if db.MySql.IsError(err) {
		return nil, errs.New(err)
	}

	//升序排序
	sort.Slice(ary, func(i, j int) bool {
		return ary[i].Id < ary[j].Id
	})

	//获取资源
	var resourceAry = make([]*chat.TblResource, 0, len(ary))
	if len(ary) > 0 {
		var idAry = make([]int64, 0, len(ary))
		for _, v := range ary {
			idAry = append(idAry, v.Id)
		}
		err = db.MySql.Table(chat.TBNResource).Where("chat_id in ? and status = 1", idAry).Find(&resourceAry).Error
		if db.MySql.IsError(err) {
			return nil, errs.New(err)
		}
	}

	//构建返回数据
	var res = &ioChat.ListResponse{
		List:   make([]*chat.Chat, 0, len(ary)),
		LastId: 0,
	}
	if len(ary) > 0 {
		res.LastId = ary[0].Id
		for _, v := range ary {
			var item = &chat.Chat{
				TblChat:   v,
				Resources: make([]*chat.TblResource, 0, 5),
			}
			for _, r := range resourceAry {
				if r.ChatId == v.Id {
					item.Resources = append(item.Resources, r)
				}
			}
			res.List = append(res.List, item)
		}
	} else {
		res.LastId = in.LastId
	}

	return &api.Response{Result: res}, nil
}

func ChatSave(c *api.Context) (resp *api.Response, err error) {
	var in = new(chat.Chat)
	c.Bind(in)

	if in.DemandId <= 0 {
		return nil, errs.New(errs.ErrorParams)
	}

	in.Creator = c.Account.Id
	in.Level = saHit.Int(in.Level == 2, 2, 1)
	in.CreateAt = saOrm.Now()

	if in.Id <= 0 || in.DemandStatus == 0 {
		var status int
		err = db.MySql.Raw("select status from demand where id = ?", in.DemandId).Scan(&status).Error
		if db.MySql.IsError(err) {
			return nil, errs.New(err)
		}
		in.DemandStatus = status
	}

	for i, v := range in.Resources {
		if v.Status == enum.Enable {
			//格式化类型
			v.Type = saHit.Int(v.Type > 0, v.Type, 10)
			v.Type = utils.FormatContent(v.Type, v.Content)
			v.Seq = i
		}
	}

	err = db.MySql.Transaction(func(tx *gorm.DB) error {
		//保存基本信息
		err = db.MySql.Table(chat.TBNChat).Save(in.TblChat).Error
		if err != nil {
			return errs.New(err)
		}

		//保存资源
		if len(in.Resources) > 0 {
			for _, v := range in.Resources {
				v.ChatId = in.TblChat.Id
			}

			err = db.MySql.Table(chat.TBNResource).Save(in.Resources).Error
			if err != nil {
				return errs.New(err)
			}
		}

		return nil
	})
	if err != nil {
		return nil, errs.New(err)
	}

	//保存基本信息
	return &api.Response{Result: in}, nil
}

func ChatUpdate(c *api.Context) (resp *api.Response, err error) {
	var in = new(ioChat.UpdateRequest)
	if in.ChatId <= 0 {
		return nil, errs.New(errs.ErrorParams)
	}

	if saData.InArray(in.Key, []string{"status", "level"}) {
		err = db.MySql.Exec(fmt.Sprintf("update chat set %s = %s where id = %d", in.Key, in.Value, in.ChatId)).Error
		if err != nil {
			return nil, errs.New(err)
		}
	} else {
		return nil, errs.New(errs.ErrorParams)
	}
	return &api.Response{Result: nil}, nil
}

func ResourceUpdate(c *api.Context) (resp *api.Response, err error) {
	var in = new(ioChat.UpdateRequest)
	if in.ResourceId <= 0 {
		return nil, errs.New(errs.ErrorParams)
	}

	if saData.InArray(in.Key, []string{"status"}) {
		err = db.MySql.Exec(fmt.Sprintf("update resource set %s = %s where id = %d", in.Key, in.Value, in.ResourceId)).Error
		if err != nil {
			return nil, errs.New(err)
		}
	} else {
		return nil, errs.New(errs.ErrorParams)
	}
	return &api.Response{Result: nil}, nil
}
